package org.rcy.ruicingmarket.config;

import org.apache.commons.lang3.StringUtils;
import org.rcy.framework.api.entity.StatusCode;
import org.rcy.framework.security.authentication.PreFormLoginAuthentication;
import org.rcy.ruicingmarket.exception.CaptchaException;
import org.rcy.ruicingmarket.login.CaptchaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author 吴康桥
 * @Description
 * @date 2022/10/28 16:52
 */

@Component
public class CaptchaAuthentication implements PreFormLoginAuthentication {
	@Autowired
	private CaptchaService captchaService;

	@Override
	public void preAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
		String sid = request.getHeader("SID");
		String code = request.getParameter("code");
		if(StringUtils.isBlank(sid)){
			throw new CaptchaException("请求头错误");
		}
		if(!captchaService.verifyCode(sid,code)) {
			throw new CaptchaException(StatusCode.VALIDATECODEERROR);
		}
	}
}
